ReactJs组件通信 您所在的位置:网站首页 react 引入js文件 ReactJs组件通信

ReactJs组件通信

#ReactJs组件通信 | 来源: 网络整理| 查看: 265

1、父与子组件通信:

我们写一个最简单的组件解释:

html (index.html):

         Title                 

我们引入react依赖的js和browser来对jsx语法解析。引入 app.js来写react组件

const list = [     'AAA',     'BBB',     'CCC',     'DDD' ]; const Item = React.createClass({     render(){         const style = this.props.actived ? {border:'1px solid green'} : {};         return {this.props.name};     } }); const Comp =  React.createClass({     getInitialState(){         return {             list : []         }     },     componentWillMount(){         this.state.list = this.props.data.map(item=>{             return {                 actived : false,                 name : item             }         })     },     componentDidMount(){         console.log('list',this.state.list);         setTimeout(()=>{             this.state.list[1].actived = true;             this.forceUpdate();         },3000)     },     callBack(item){         console.log(item.name);     },     render(){         return              {this.state.list.map(item=> )}              } }); ReactDOM.render(                            ,     document.getElementById('container') );

这里我们定义了Comp 组件,给了name和data属性,在组件加载前初始化数据(componentWillMount),通过this.props.data.map的方式获取父类的属性值进行遍历。

2、子组件与父通信:

子组件如何调用父组件呢? 我们在父组件Comp的render中 Item 上加入 

callBack={this.callBack.bind(this,item)}

bind自身并传递item参数,同时在父组件中完善callBack方法:

callBack(item){         console.log(item.name);     },

在子组件item中,通过添加点击事件

onClick={this.props.callBack}

我们就可以轻松的与父组件通信了。

2、事件总线通信:

说起来觉得不好理解,其实就是通过事件监听的方式实现,这里我们用一个插件来描述,通过bower安装eventemitter

bower install eventemitter

reactjs通信1.JPG

我们在index.html中引入eventemitter

做一个颜色切换的小插件,插件比较弱智,但是能说明问题:

const eventbus = new eventemitter.EventEmitter(); const Comp  =  React.createClass({     getInitialState(){         return {             colorIndex : 0,             colors : ['yellow','red']         }     },     componentWillMount(){         eventbus.on('changeColor',(id,color)=>{             if(this.props.id != id && this.state.colors[this.state.colorIndex] == color){                 this.changeColor();             }         })     },     changeColor(){         this.setState({             colorIndex : this.state.colorIndex ? 0 : 1         });         setTimeout(()=>{                 eventbus.emit('changeColor',this.props.id,this.state.colors[this.state.colorIndex])         },1500)     },     render(){         return (                              

{this.props.name}

                click me                      )     } }); ReactDOM.render(                                 ,     document.getElementById('container') );

这里定义了两个Comp插件,通过点击按钮来切换背景颜色,同时发送事件,更改另一个插件为不同的颜色

reactjs通信2.JPG

const eventbus = new eventemitter.EventEmitter();

来实例化一个event对象,它有两个方法: 

eventbus.on() // 事件监听 eventbus.emit() // 事件发送

了解node 事件系统的对这个就比较熟悉了。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有